import express from 'express'
import Message from '../models/message'
import {auth} from '../middleware'
import formidable from 'formidable'
let fs = require('fs')

const router = express.Router();

function isFormData(req) {
  let type = req.headers['content-type'] || ''
  return type.includes('multipart/form-data')
}

router.post('/uploadVoice', function (req, res, next) {


  let filename = ''

  if (!isFormData(req)) {
    res.statusCode = 400
    res.end('错误的请求, 请用multipart/form-data格式')
    return
  }


  let form = new formidable.IncomingForm()
  form.uploadDir = './voice'
  form.keepExtensions = true

  form.on('field', (field, value) => {
    console.log(field)
    console.log(value)
  })

  form.on('file', (name, file) => {
    // 重命名文件
    let types = file.name.split('.')
    let suffix = types[types.length - 1]
    filename = new Date().getTime() + '.' + suffix
    fs.renameSync(file.path, './voice/' + filename)
  })

  form.on('progress', (bytesReceived, bytesExpected) => {
    let percent = Math.floor(bytesReceived / bytesExpected * 100)
    console.log(percent)
  })

  form.on('end', () => {
    console.log('上传成功')
    res.json({
      errno: 0,
      filename,
      msg: '上传成功'
    })
  })

  form.on('error', err => {
    console.log(err)
  })

  form.parse(req)
})


router.post('/uploadImage', function (req, res, next) {


  let filename = ''

  if (!isFormData(req)) {
    res.statusCode = 400
    res.end('错误的请求, 请用multipart/form-data格式')
    return
  }


  let form = new formidable.IncomingForm()
  form.uploadDir = './image'
  form.keepExtensions = true

  form.on('field', (field, value) => {
    console.log(field)
    console.log(value)
  })

  form.on('file', (name, file) => {
    // 重命名文件
    let types = file.name.split('.')
    let suffix = types[types.length - 1]
    filename = new Date().getTime() + '.' + suffix
    fs.renameSync(file.path, './image/' + filename)
  })

  form.on('progress', (bytesReceived, bytesExpected) => {
    let percent = Math.floor(bytesReceived / bytesExpected * 100)
    console.log(percent)
  })

  form.on('end', () => {
    console.log('上传成功')
    res.json({
      errno: 0,
      filename,
      msg: '上传成功'
    })
  })

  form.on('error', err => {
    console.log(err)
  })

  form.parse(req)
})

export default router
